package com.meitianhui.convenitenbuy.module.home.ui.activity.web;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.google.gson.reflect.TypeToken;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseWebViewActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.hyphenate.ui.ChatActivity;
import com.meitianhui.convenitenbuy.module.home.contract.BrandWebViewContract;
import com.meitianhui.convenitenbuy.module.home.di.DaggerHomeComponent;
import com.meitianhui.convenitenbuy.module.home.di.HomeModule;
import com.meitianhui.convenitenbuy.module.home.model.bean.OneOrder;
import com.meitianhui.convenitenbuy.module.home.presenter.BrandWebViewPresenter;
import com.meitianhui.convenitenbuy.module.home.ui.activity.HomeOrderActivity;
import com.meitianhui.convenitenbuy.module.mine.model.UserAsset;
import com.meitianhui.convenitenbuy.module.order.ui.activity.OrderPayActivity;
import com.meitianhui.convenitenbuy.module.store.ui.activity.StoreDetailActivity;
import com.meitianhui.convenitenbuy.util.GsonParserUtils;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.TipUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import javax.inject.Inject;

/**
 * Created by Administrator on 2017/11/14.
 * 品牌领
 */

public class BrandWebViewActivity extends BaseWebViewActivity implements BrandWebViewContract.View {
    private HashMap<String, String> mTitleMap = new HashMap<>();// 存放url和上一个界面的标题
    private boolean mIsSecond = false;
    private boolean mIsSecondList = false;
    private boolean mIsFromEdinburgh = false;   //品牌领跳转
    @Inject
    BrandWebViewPresenter presenter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerHomeComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
        if (!TextUtils.isEmpty(mTitle)) {
            setTbTitle(mTitle);
        }
        mCurrentName = "品牌领";
        setTbMenu(R.mipmap.icon_title_share);
        initData();
        mWebView.addJavascriptInterface(new MyJavaScriptInterface(this), "jsObj");//js调用安卓
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    }


    private void initData() {
        mIsSecond = getIntent().getBooleanExtra("is_second", false);
        mIsSecondList = getIntent().getBooleanExtra("is_second_list", false);
        if (url.contains("detail") || url.contains("publish")) {
            mIsSecond = true;
        } else if (url.contains("list")) {
            mIsSecondList = true;
        } else {
            mIsFromEdinburgh = getIntent().getBooleanExtra("is_from_edinburgh", false);
        }
        if (mIsSecond) {
            setTbMenu(R.mipmap.icon_title_share);
        } else {
            setTbMenu(R.mipmap.icon_title_detail);
        }
    }


    @Override
    protected void clickMenu() {
        super.clickMenu();
        if (mIsSecond) {
            share(Constants.TYPE_NO_SHOW_WXMINI_SHARE);
        } else {
            if (!InfoProvider.getLoginStatus(BrandWebViewActivity.this)) {
                JumpUtil.jumpToLoginActivity(0, BrandWebViewActivity.this, 0, "");
                return;
            }
            Intent intent = new Intent(BrandWebViewActivity.this, HomeOrderActivity.class);
            startActivity(intent);

        }

    }


    @Override
    protected void urlLoading(WebView view, String url) {
        if (!mIsSecond) {
            if (url.contains("detail") || url.contains("publish")) {
                Intent intent = new Intent(BrandWebViewActivity.this, BrandWebViewActivity.class);
                intent.putExtra("url", url);
                intent.putExtra("title", "品牌领");
                intent.putExtra("is_second", true);
                startActivity(intent);
            } else if (url.contains("list")) {
                Intent intent = new Intent(BrandWebViewActivity.this, BrandWebViewActivity.class);
                intent.putExtra("url", url);
                intent.putExtra("title", "品牌领");
                intent.putExtra("is_second_list", true);
                startActivity(intent);
            } else {
                view.loadUrl(url);
            }
        } else {
            view.loadUrl(url);
        }
    }

    @Override
    protected void receivedTitle(WebView view, String title) {

    }

    @Override
    protected void onRefreshData() {

    }

    @Override
    protected void isFinish() {
        if (mWebView.canGoBack()) {
            String currentUrl = mWebView.getUrl();
            if (mTitleMap.isEmpty() || TextUtils.isEmpty(mTitleMap.get(currentUrl))) {
            } else {
                mTitleMap.remove(currentUrl);
            }
            mWebView.goBack();
        } else {
            finish();
            mTitleMap.clear();
        }
    }

    /**
     * 小程序分享
     * @param v
     */
    @Override
    protected void shareWxMini(View v) {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void getUserAssetSuccess(UserAsset userAsset, OneOrder oneOrder) {
        if (userAsset != null) {
            if (Integer.valueOf(userAsset.getGold()) < 0) {
                TipUtils.showToast(App.getInstance(), "金币余额不足,支付取消");
            } else {
                Intent it = new Intent(BrandWebViewActivity.this, OrderPayActivity.class);
                it.putExtra("order_info", oneOrder);
                it.putExtra("from_page", Constants.TYPE_GOLD_BUY);
                startActivity(it);
            }
        }
    }

    //js调用安卓代码
    private class MyJavaScriptInterface {
        private Context mContext;
        private Handler handler = new Handler();

        public MyJavaScriptInterface(Context c) {
            this.mContext = c;
        }

        //店东ID
        @JavascriptInterface
        public void showStore(String store_id) {
            try {
                JSONObject jsonObject=new JSONObject(store_id);
                String storesId=jsonObject.getString("stores_id");
                Intent intent = new Intent(BrandWebViewActivity.this, StoreDetailActivity.class);
                intent.putExtra("store_id",storesId);
                startActivity(intent);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        //打开广告页
        @JavascriptInterface
        public void openAdLayer(final String jsonData) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject jsonObject = new JSONObject(jsonData);
                        String url = jsonObject.getString("url");
                        Intent intent = new Intent(BrandWebViewActivity.this, AdWebViewActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
        }

        //返回按钮
        @JavascriptInterface
        public void closeWebView() {
            BrandWebViewActivity.this.finish();
        }

        //金币兑支付
        @JavascriptInterface
        public void exchangeNow(String shopBean) {
            TypeToken<OneOrder> types = new TypeToken<OneOrder>() {
            };
            OneOrder oneOrder = null;
            try {
                oneOrder = GsonParserUtils.getInstance().fromJson(shopBean, types);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (InfoProvider.getLoginStatus(BrandWebViewActivity.this)) {
                presenter.getUserAsset(oneOrder);
            } else {
                JumpUtil.jumpToLoginActivity(0, BrandWebViewActivity.this, 0, "");
                return;
            }
        }

        //客服功能
        @JavascriptInterface
        public void chatWithCustomerServiceAgent(final String chat) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (!InfoProvider.getLoginStatus(BrandWebViewActivity.this)) {
                            JumpUtil.jumpToLoginActivity(0, BrandWebViewActivity.this, 0, "");
                            return;
                        }
                        JSONObject jsonObject = new JSONObject(chat);
                        String chatid = jsonObject.getString("chat_id");
                        String title = jsonObject.getString("title");
                        String hand = jsonObject.getString("head_pic_path");
                        Intent intent = new Intent(BrandWebViewActivity.this, ChatActivity.class);
                        intent.putExtra("userId", chatid);
                        intent.putExtra("groupName", title);
                        startActivity(intent);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, 0);
        }

        @JavascriptInterface
        public void share(String s_1) {
            if (!TextUtils.isEmpty(s_1)) {
                try {
                    JSONObject jsonObject = new JSONObject(s_1);
                    mShareTitle = jsonObject.getString("title");
                    mShareDesc = jsonObject.getString("desc");
                    mShareImgPath = jsonObject.getString("imgPath");
                    mShareUrl = jsonObject.getString("url");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView.canGoBack()) {
                String currentUrl = mWebView.getUrl();
                if (mTitleMap.isEmpty() || TextUtils.isEmpty(mTitleMap.get(currentUrl))) {
                } else {
                    mTitleMap.remove(currentUrl);
                }
                mWebView.goBack();
            } else {
                finish();
                mTitleMap.clear();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
